/*
 * Command analyse function
 * Info:
 * This c file is used for analyzing commands and check what should happen.
 * The original c file was written by Roy Stegers and Gino Biervliet.
 * Edited by Kevin Ouwens for FSP usage.
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include <strings.h>
#include "hfile.h"

void *clientThread(int clientNo);

int commandAna(char *buffer)
{
    int iCount = 0, i = 0, n = 0;
    char splitBuff[CMDSIZE][ARGSIZE]; 
    printf("dataBuffer: %s\n", buffer);
    printf("passed, length = %d\n", strlen(buffer));
    //sleep(10); //debug purposes
    //substract the command and arguments, because we can and should 
    for(iCount=0;iCount<2;iCount++)
    {
        if(iCount!=1)
        {
            for(n=0;buffer[i] != ' ';n++)
            {
                //printf("n:%d\ni:%d\niCount:%d\n", n, i, iCount);
                splitBuff[iCount][n] = buffer[i];
                i++;
            }
            i++;
            splitBuff[iCount][i] = '\0';
        }
        else
        {
            for(n=0;buffer[i] != '\0';n++)
            {
                //printf("n:%d\ni:%d\niCount:%d\n", n, i, iCount);
                splitBuff[iCount][n] = buffer[i];
                i++;
            }
            i-2;
            splitBuff[iCount][i] = '\0';
            break;
        }
    }
    
    //end of substraction

    printf("command: %s\n", splitBuff[0]);
    printf("arg1: %s\n", splitBuff[1]);
    //printf("arg2: %s\n", splitBuff[2]);

    //compare the command to whatever to see what should be done.
    if(strcmp(splitBuff[0], "NEWCLIENT")==0)
    {
        //do something with thread.c
        int clientNo = atoi(splitBuff[1]); //get the clientnumber
        printf("NEWCLIENT function called, clientNo: %d\n", clientNo);
        //send the clientnumber to createClientThread() function in thread.c
        createClientThread(clientNo);
        bzero(splitBuff[0], strlen(splitBuff[0]));
        bzero(splitBuff[1], strlen(splitBuff[1]));
        return 0;
    }
    else
    {
        printf("invalid command\n");
        return 0;
    }
    //end of comparison
    
    bzero(buffer,CHUNKSIZE);
    bzero(splitBuff,CHUNKSIZE);
    return 0;
}